//
//  UUProductEditVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 03/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUProductEditVC.h"
#import "UUHybridManager+CharterSupplier.h"
#import "UUProductManager.h"
#import "UUFleetManager.h"
#import "UUPermissionManager.h"
#import "UUProductUtility.h"
#import <UUFoundation/UIBarButtonItem+CustomButton.h>

@interface UUProductEditVC () <UUProductManagerObserver>

@property (nonatomic, strong) UUProductModel *product;

@end

@implementation UUProductEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.productId != nil) {
        self.product = [GetProductManager() fetchProductModelWithProductId:self.productId];
        [GetProductManager() addObserver:self];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateApplicationStatus {
    if (![GetPermissionManager() checkPermission:UUPermissionFlagProductReadWrite]) {
        return;
    }
    
    if (self.product) {
        switch (self.product.onlineStatus) {
            case UUProductOnlineStatusOffline:
                break;
            case UUProductOnlineStatusApplicationToOffline:
                self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"取消申请" target:self selector:@selector(cancelApplication)];
                break;
            case UUProductOnlineStatusOnline:
                self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"申请下架" target:self selector:@selector(applicationToOffline)];
                break;
            default:
                DKAssert(0);
                break;
        }
    }
}

- (void)applicationToOffline {
    [UIAlertController presentAlertControllerWithTitle:@"提示" message:@"下架申请通过后，用户将无法购买此产品，但已售产品必须完成服务，确定？"
                                             doneBlock:^{
                                                 ShowIndicator();
                                                 WEAK_SELF();
                                                 [GetProductManager() asyncApplicationToOfflineWithProductId:self.productId completeBlock:^(NSError *error) {
                                                     HideTipsOnView(weakSelf.view);
                                                     
                                                     if (error != nil) {
                                                         ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                     }
                                                 }];
                                             } cancelBlock:nil];
}

- (void)cancelApplication {
    [UIAlertController presentAlertControllerWithTitle:@"提示" message:@"确定取消下架申请？" doneBlock:^{
        ShowIndicator();
        WEAK_SELF();
        [GetProductManager() asyncCancelApplicationToOfflineWithProductId:self.productId completeBlock:^(NSError *error) {
            HideTipsOnView(weakSelf.view);
            
            if (error != nil) {
                ShowTipsOnView(error.localizedDescription, weakSelf.view);
            }
        }];
    } cancelBlock:nil];
}

- (void)formDidLoad {
    [super formDidLoad];
    
    [self updateApplicationStatus];
}

- (void)reloadForm {
    [super reloadForm];
    
    [self updateApplicationStatus];
}

- (NSString *)name {
    return @"产品";
}

- (BOOL)isAdd {
    return self.productId == nil;
}

- (BOOL)canEdit {
    return [GetPermissionManager() checkPermission:UUPermissionFlagProductReadWrite] && self.product.onlineStatus == UUProductOnlineStatusOffline;
}

- (NSURLRequest *)editRequest {
    return GetHybridManager().productEditURLRequest;
}

- (NSURLRequest *)detailRequest {
    return GetHybridManager().productDetailURLRequest;
}

- (void)enterEditVC {
    if (self.product.onlineStatus == UUProductOnlineStatusOffline && self.product.status == UUProductReviewStatusApproval) {
        [UIAlertController presentAlertControllerWithTitle:@"重新编辑提交后该产品需要进行重新审核" message:nil doneBlock:^{
            [super enterEditVC];
        } cancelBlock:nil];
    } else {
        [super enterEditVC];
    }
}

- (void)configEditVC:(UUProductEditVC *)editVC {
    editVC.productId = self.productId;
}

- (NSDictionary *)previewFields {
    if (self.product) {
        UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:self.product.fleetId];
        UUCarCategoryModel *carCategory = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:self.product.carCategoryId];
        
        NSMutableArray<NSDictionary *> *specDicts = [NSMutableArray arrayWithCapacity:self.product.spec.count];
        for (UUProductSpecModel *model in self.product.spec) {
            [specDicts addObject:[UUProductUtility convertProductSpecModelToFormDict:model]];
        }
        
        return @{
                 @"motorcade_id" : fleet.fleetId ?: @"",
                 @"motorcade_name" : fleet.name ?: @"",
                 @"bus_category_id" : carCategory.id,
                 @"bus_category_name" : carCategory.name,
                 @"status" : @(self.product.status),
                 @"online_status" : @(self.product.onlineStatus),
                 @"spec" : specDicts,
                 @"remark" : self.product.remark ?: @"",
                 };
    } else {
        if (self.preferredCarCategoryId == nil) {
            return nil;
        } else {
            UUCarCategoryModel *carCategory = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:self.preferredCarCategoryId];
            
            if (carCategory) {
                return @{
                         @"bus_category_id" : carCategory.id,
                         @"bus_category_name" : carCategory.name,
                         };
            } else {
                return nil;
            }
        }
    }
}

- (void)addOrUpdate:(NSDictionary *)data {
    NSNumber *carCategoryId = data[@"bus_category_id"];
    NSNumber *fleetId = data[@"motorcade_id"];
    
    NSArray<NSDictionary *> *specDicts = data[@"spec"];
    NSMutableArray<UUProductSpecModel *> *spec = [NSMutableArray arrayWithCapacity:specDicts.count];
    for (NSDictionary *specDict in specDicts) {
        [spec addObject:[[UUProductSpecModel alloc] initWithData:specDict]];
    }
    
    ShowIndicator();
    WEAK_SELF();
    [GetProductManager() asyncUpdateProductWithProductId:self.productId
                                           carCategoryId:carCategoryId
                                                 fleetId:fleetId
                                                    spec:spec
                                           completeBlock:^(NSError *error) {
                                               HideTipsOnView(weakSelf.view);
                                               
                                               if (error == nil) {
                                                   [weakSelf.navigationController popViewControllerAnimated:YES];
                                               } else {
                                                   ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                               }
                                           }];
}

#pragma mark - UUProductManagerObserver methods

- (void)productManagerDidUpdateProducts:(NSArray<NSNumber *> *)products {
    if ([products containsObject:self.productId]) {
        self.product = [GetProductManager() fetchProductModelWithProductId:self.productId];
        [self reloadForm];
    }
}

@end
